﻿using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using System.Net.Http.Json;
using System.Collections.Generic;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Web;
using AntDesign;
using ImoviesBlazorAntPro.Shared.Dtos;

namespace ImoviesBlazorAntPro.Client.Pages.Admin
{
    public partial class AnimationVlinkManage
    {
        [Inject]
        HttpClient HttpClient { get; set; }
        [Inject]
        IMessageService MessageService { get; set; }
        [Inject]
        ModalService ModalService { get; set; }


        private string _videoId;
        private bool _loading = false;


        private List<AnimationDto> videos = new List<AnimationDto>();
        private List<AnimationVlinkDto> dataList = new List<AnimationVlinkDto>();
        private IEnumerable<AnimationVlinkDto> selectedRows;

        private class TempData
        {
            public List<AnimationVlinkDto> Data { get; set; } = new List<AnimationVlinkDto>();
            public int Total { get; set; }
        }

        /// <summary>
        /// 显示添加对话框
        /// </summary>
        private void ShowAddModal()
        {
            if (string.IsNullOrEmpty(_videoId))
            {
                MessageService.Warning("请选择视频再操作", 2);
                return;
            }
            addModel.AnimationId = _videoId;
            addModel.Name = string.Empty;
            addModel.Url = string.Empty;
            addModel.RealUrl = string.Empty;
            _addModalVisible = true;
        }


        /// <summary>
        /// 显示编辑对话框
        /// </summary>
        /// <param name="obj"></param>
        private void ShowEditModal(AnimationVlinkDto obj)
        {
            editModel.Id = obj.Id;
            editModel.AnimationId = _videoId;
            editModel.Name = obj.Name;
            editModel.Url = obj.Url;
            editModel.RealUrl = obj.RealUrl;
            _editModalVisible = true;
        }


        /// <summary>
        /// 删除单个
        /// </summary>
        /// <param name="id"></param>
        private async Task ConfirmDeleteAsync(uint id)
        {
            var res = await HttpClient.DeleteAsync($"/api/animationVlink/{id}");
            if (!res.IsSuccessStatusCode)
            {
                await MessageService.Error("操作失败", 2);
                return;
            }
            MessageService.Success("操作成功", 1.5);
            // 重载数据
            var resp = await HttpClient.GetAsync($"/api/animation/vlist/{_videoId}");
            dataList = JsonSerializer.Deserialize<List<AnimationVlinkDto>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
        }


        /// <summary>
        /// 批量删除
        /// </summary>
        private async void BatchDelete()
        {
            if (selectedRows == null)
            {
                MessageService.Warning("请选择视频", 2);
                return;
            }

            ModalService.Confirm(new ConfirmOptions()
            {
                Title = "确定进行批量删除吗?",
                OkType = "danger",
                OkText = "确定",
                CancelText = "取消",
                OnOk = async (e) =>
                {
                    var ids = selectedRows.Select(x => x.Id).ToList();
                    var res = await HttpClient.PostAsJsonAsync("/api/animationVlink/batchDetele", ids);
                    if (!res.IsSuccessStatusCode)
                    {
                        MessageService.Error("操作失败", 2);
                        return;
                    }
                    MessageService.Success("操作成功", 1.5);
                    // 重载数据
                    var resp = await HttpClient.GetAsync($"/api/animation/vlist/{_videoId}");
                    dataList = JsonSerializer.Deserialize<List<AnimationVlinkDto>>(await resp.Content.ReadAsStringAsync(),
                     new JsonSerializerOptions
                     {
                         PropertyNameCaseInsensitive = true,
                         IncludeFields = true,
                     });
                },
            });
        }


        /// <summary>
        /// 视频选择切换事件
        /// </summary>
        /// <param name="vid"></param>
        private async Task VideoSelectedChangeAsync(string vid)
        {
            _loading = true;
            dataList.Clear();
            var resp = await HttpClient.GetAsync($"/api/animation/vlist/{vid}");
            dataList = JsonSerializer.Deserialize<List<AnimationVlinkDto>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
            _loading = false;
        }


        /// <summary>
        /// 加载完毕事件
        /// </summary>
        /// <returns></returns>
        protected override async Task OnInitializedAsync()
        {
            HttpClient.DefaultRequestHeaders.Add("X-Req-Origin", "Admin");
            var resp = await HttpClient.GetAsync("/api/animation/all");
            videos = JsonSerializer.Deserialize<List<AnimationDto>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
        }


        #region 添加表单相关操作

        private bool _addModalVisible = false;
        private AnimationVlinkForCreateDto addModel = new AnimationVlinkForCreateDto();
        private Form<AnimationVlinkForCreateDto> _addForm;

        /// <summary>
        /// 提交失败
        /// </summary>
        /// <param name="editContext"></param>
        private void OnAddFormFinishFailed(EditContext editContext)
        {
            //Console.WriteLine($"Failed:{JsonSerializer.Serialize(model)}");
        }


        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="e"></param>
        private void HandleAddModalCancel(MouseEventArgs e)
        {
            _addModalVisible = false;
        }


        /// <summary>
        /// 表单提交后关闭 modal
        /// </summary>
        /// <param name="editContext"></param>
        private void OnAddFormFinish(EditContext editContext)
        {
            _addModalVisible = false;
        }

        /// <summary>
        /// 点击modal的OK按钮提交表单
        /// </summary>
        /// <param name="e"></param>
        private async Task HandleAddModalOkAsync(MouseEventArgs e)
        {
            if (!_addForm.Validate())
            {
                return;
            }
            var data = new AnimationVlinkForCreateDto
            {
                AnimationId = addModel.AnimationId,
                Name = addModel.Name,
                Url = addModel.Url,
                RealUrl = addModel.RealUrl,
            };
            var res = await HttpClient.PostAsJsonAsync<AnimationVlinkForCreateDto>("/api/animationVlink", data);
            if (!res.IsSuccessStatusCode)
            {
                await MessageService.Error("操作失败", 2);
                return;
            }
            // 重载数据
            var resp = await HttpClient.GetAsync($"/api/animation/vlist/{_videoId}");
            dataList = JsonSerializer.Deserialize<List<AnimationVlinkDto>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
            MessageService.Success("操作成功", 1.5);
            _addForm.Reset();
            _addModalVisible = false;
        }

        #endregion




        #region 编辑表单相关操作

        bool _editModalVisible = false;
        private AnimationVlinkForUpdateDto editModel = new AnimationVlinkForUpdateDto();
        private Form<AnimationVlinkForUpdateDto> _editForm;

        /// <summary>
        /// 提交失败
        /// </summary>
        /// <param name="editContext"></param>
        private void OnEditFormFinishFailed(EditContext editContext)
        {
            //Console.WriteLine($"Failed:{JsonSerializer.Serialize(model)}");
        }


        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="e"></param>
        private void HandleEditModalCancel(MouseEventArgs e)
        {
            _editModalVisible = false;
        }


        /// <summary>
        /// 表单提交后关闭 modal
        /// </summary>
        /// <param name="editContext"></param>
        private void OnEditFormFinish(EditContext editContext)
        {
            _editModalVisible = false;
        }

        /// <summary>
        /// 点击modal的OK按钮提交表单
        /// </summary>
        /// <param name="e"></param>
        private async Task HandleEditModalOkAsync(MouseEventArgs e)
        {
            if (!_editForm.Validate())
            {
                return;
            }
            var data = new AnimationVlinkForUpdateDto
            {
                Id = editModel.Id,
                AnimationId = editModel.AnimationId,
                Name = editModel.Name,
                Url = editModel.Url,
                RealUrl = editModel.RealUrl,
            };
            var res = await HttpClient.PutAsJsonAsync<AnimationVlinkForUpdateDto>("/api/animationVlink", data);
            if (!res.IsSuccessStatusCode)
            {
                await MessageService.Error("操作失败", 2);
                return;
            }

            // 重载数据
            var resp = await HttpClient.GetAsync($"/api/animation/vlist/{_videoId}");
            dataList = JsonSerializer.Deserialize<List<AnimationVlinkDto>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
            MessageService.Success("操作成功", 1.5);
            _editForm.Reset();
            _editModalVisible = false;
        }

        #endregion
    }
}
